<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactTodo\Action\Workbench;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactTodo\Contract\ContactTodoContract;
use MoChat\Plugin\ContactTrack\Contract\ContactTrackContract;

/**
 * 添加待办.
 *
 * Class Store
 * @Controller
 */
class Update extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContact;

    /**
     * @Inject
     * @var ContactTodoContract
     */
    protected $contactTodoService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployee;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * 互动轨迹表.
     * @Inject
     * @var ContactTrackContract
     */
    private $track;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/contactTodo/update", methods="PUT")
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        // 接收参数
        $params = [
            'todoId' => (int) $this->request->input('todoId', 0),
            'type' => (int) $this->request->input('type'),
            'contactId' => (int) $this->request->input('contactId'),
            'timingRemind' => $this->request->input('timingRemind', []),
            'cycleRemind' => $this->request->input('cycleRemind', []),
        ];
        // 校验参数
        $this->validated($params);
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];

        $employee = $this->workEmployee->getWorkEmployeeById($params['employeeId'], ['wx_user_id']);
        $contact = $this->workContact->getWorkContactById($params['contactId'], ['wx_external_userid']);
        // 数据操作
        Db::beginTransaction();
        try {
            // 定时提醒
            if ($params['type'] === 1) {
                if (empty($params['timingRemind'])) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '定时提醒为空，不可操作');
                }
                foreach ($params['timingRemind'] as $item) {
                    $data = [
                        'type' => $params['type'],
                        'employee_id' => $params['employeeId'],
                        'content' => $item['content'],
                        'wx_user_id' => $employee['wxUserId'],
                        'day' => $item['day'],
                        'time' => $item['time'],
                    ];
                    // 添加待办
                    $id = $this->contactTodoService->updateContactTodoById($params['todoId'], $data);
                }
            }
            // 周期提醒
            if ($params['type'] === 2) {
                if (empty($params['cycleRemind'])) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '周期提醒为空，不可操作');
                }
                $data = [
                    'type' => $params['type'],
                    'content' => $params['cycleRemind']['content'],
                    'wx_user_id' => $employee['wxUserId'],
                    'day' => $params['cycleRemind']['day'],
                    'time' => $params['cycleRemind']['time'],
                    'repeat' => empty($params['cycleRemind']['repeat']) ? '{}' : Json::encode($params['cycleRemind']['repeat']),
                    'end_repeat' => empty($params['cycleRemind']['endRepeat']) ? '{}' : Json::encode($params['cycleRemind']['endRepeat']),
                ];
                // 添加待办
                $id = $this->contactTodoService->updateContactTodoById($params['todoId'], $data);
            }

            Db::commit();
            return [];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加待办失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'type' => 'required',
            'contactId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'type.required' => '类型 必传',
            'contactId.required' => '客户id必传',
        ];
    }
}
